package org.robot.scm.infra;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CompletableFuture;
import lombok.extern.slf4j.Slf4j;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.proxy.ProxyInfo;
import org.robot.scm.utils.JsonHelper;
import org.robot.scm.utils.RequestHelper;

@Slf4j
public class ProxyLoaderHelper implements Runnable {

    private static final String PROXY_KEY = "proxy_ip_list";

    public static void loadProxy() {
        try {
            List<ProxyInfo> ips = Lists.newArrayList();
            String result = RequestHelper.get(BaseConfig.PROXY);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONArray data = (JSONArray) jsonObject.get("data");
            if (Objects.nonNull(data)) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject dataObj = data.getJSONObject(i);
                    ips.add(new ProxyInfo(dataObj.getString("ip"), Integer.parseInt(dataObj.getString("port"))));
                }
            }
            if (!ips.isEmpty()) {
                log.info("get ip success, ips: {}", ips);
                LocalCacheHelper.remove(PROXY_KEY);
                LocalCacheHelper.put(PROXY_KEY, JsonHelper.toJSONString(ips));
            }
        } catch (Exception ignored) {
        }
    }

    public static void start() {
        CompletableFuture.runAsync(ProxyLoaderHelper::new);
    }

    /**
     * 15秒更新一次,短效IP失效为2分钟
     */
    @Override
    public void run() {
        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                loadProxy();
            }
        }, 0L, 15000L);
    }
}
